#include "logcommon.h"

namespace afcore {
namespace log {

/// @brief  日志名称
static RStringView g_log_level_names[] { "trace", "debug", "info", "warn", "error", "fatal", "off" };
/// @brief  日志名称缩写
static const char* g_log_level_short_names[] { "T", "D", "I", "W", "E", "F", "O" };

RStringView& ToStringView(ELogLevel l) noexcept {
  return g_log_level_names[l];
}

const char* ToShortCStr(ELogLevel l) noexcept {
  return g_log_level_short_names[l];
}

ELogLevel ToLevelEnum(const std::string& name) noexcept {
  uint8_t level = 0;
  for (const auto& l : g_log_level_names) {
    if (0 == l.compare(name)) {
      return static_cast<ELogLevel>(level);
    }
    ++level;
  }

  if ("warn" == name) {
    return kLogLevelWarn;
  }

  if ("error" == name) {
    return kLogLevelError;
  }

  return kLogLevelOff;
}

CLogException::CLogException(std::string msg)
  : msg_(std::move(msg)) {
}

CLogException::CLogException(const std::string &msg, int last_errno) {
  RMemoryBuf buf;
  fmt::format_system_error(buf, last_errno, msg);
  msg_ = fmt::to_string(buf);
}

const char* CLogException::what() const noexcept {
  return msg_.c_str();
}

void ThrowCLogeException(const std::string &msg, int last_errno) {
  throw(CLogException(msg, last_errno));
}

void ThrowCLogeException(std::string msg) {
  throw(CLogException(std::move(msg)));
}


} // !namespace log
} // !namespace afcore